<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

</head>

<body>
    <input type="text" name="" id="ipt">
    <input type="text" name="" id="pwd">
    <button id="btn">登录</button>
    <script>



        // https://www.cnblogs.com/huiguo/p/16601076.html

        const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");  //十六位十六进制数作为密钥
        const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412');   //十六位十六进制数作为密钥偏移量
        //解密方法
        function Decrypt(word) {
            let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
            let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
            let decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
            let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
            return decryptedStr.toString();
        }
        //加密方法
        function Encrypt(word) {
            let srcs = CryptoJS.enc.Utf8.parse(word);
            let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
            return encrypted.ciphertext.toString().toUpperCase();
        }
        /*
            1-- 点击登录按钮的时候，获取输入框的值，存入本地
            2-- 打开了页面--立刻获取本地存入的username对于的值
        */
        var btn = document.querySelector("#btn");
        var ipt = document.querySelector('#ipt');
        var pwdIpt = document.querySelector('#pwd');


        btn.onclick = function () {
            var username = ipt.value;
            var password = pwdIpt.value;
            console.log(username);
            // 存入本地
            localStorage.setItem('username', username)


            // 要加密的明文
            // var plaintext = "Hello, World!";



            // 加密


            // 输出密文
            let r = Encrypt(password)
            localStorage.setItem('pwd', r)
        }

        // 2-
        // 打开了页面--立刻获取本地存入的username对于的值
        var username = localStorage.getItem('username')

        var password = localStorage.getItem('pwd')
        var r2 = Decrypt(password)



        console.log(r2);
        console.log(username);
        // 判断 读取出来的数据  username  是否 为 null
        // 不为null  就把 变量 usrname的值 赋值输入框的value
        if (username != null) {
            ipt.value = username;
        }




    </script>

</body>

</html>